﻿#include "HeartBeatManager.h"

#include "TcpIOer.h"
#include "TcpCodec.h"
#include "UserRegisterCodec.h"

HeartBeatManager::HeartBeatManager()
{
  connect(&timer_sendHeartBeat,&QTimer::timeout,this,&HeartBeatManager::slot_sendHeartBeat);
}

HeartBeatManager::~HeartBeatManager()
{

}

void HeartBeatManager::updateHeartBeat()
{
  tcpIOer->setCountDown(timeout);
}

void HeartBeatManager::slot_registerStateChanged(uchar state)
{
  switch (state)
    {
    case UserRegisterCodec::Register:
      timer_sendHeartBeat.start(interval);
      break;
    case UserRegisterCodec::Unregister:
      timer_sendHeartBeat.stop();
      break;
    }
}

void HeartBeatManager::slot_disconnected()
{
  timer_sendHeartBeat.stop();
}

void HeartBeatManager::slot_sendHeartBeat()
{
  DataPackage_TcpCodec dataPackage_TcpCodec;
  tcpCodec->code((&dataPackage_TcpCodec)
                 ->setPackageType(TcpCodec::HeartBeat)
                 ->setData(QByteArray()));
}

TcpIOer* HeartBeatManager::getTcpIOer()const
{
  return tcpIOer;
}

HeartBeatManager* HeartBeatManager::setTcpIOer(TcpIOer*const tcpIOer)
{
  if(Q_NULLPTR!=this->tcpIOer)
    {
      disconnect(this->tcpIOer,&TcpIOer::disconnected,this,&HeartBeatManager::slot_disconnected);
    }
  this->tcpIOer=tcpIOer;
  if(Q_NULLPTR!=this->tcpIOer)
    {
      connect(this->tcpIOer,&TcpIOer::disconnected,this,&HeartBeatManager::slot_disconnected);
      printInjection(this,tcpIOer);
    }
  return this;
}

TcpCodec* HeartBeatManager::getTcpCodec()const
{
  return tcpCodec;
}

HeartBeatManager* HeartBeatManager::setTcpCodec(TcpCodec*const tcpCodec)
{
  this->tcpCodec=tcpCodec;
  printInjection(this,tcpCodec);
  return this;
}

UserRegisterCodec* HeartBeatManager::getUserRegisterCodec()const
{
  return userRegisterCodec;
}

HeartBeatManager* HeartBeatManager::setUserRegisterCodec(UserRegisterCodec* const userRegisterCodec)
{
  if(Q_NULLPTR!=this->userRegisterCodec)
    {
      disconnect(this->userRegisterCodec,&UserRegisterCodec::signal_registerState,this,&HeartBeatManager::slot_registerStateChanged);
    }
  this->userRegisterCodec=userRegisterCodec;
  if(Q_NULLPTR!=this->userRegisterCodec)
    {
      connect(this->userRegisterCodec,&UserRegisterCodec::signal_registerState,this,&HeartBeatManager::slot_registerStateChanged);
      printInjection(this,userRegisterCodec);
    }
  return this;
}

void HeartBeatManager::objectAutoInjection(QHash<QString,QObject*>* objMap)
{
  setTcpIOer(getObjFromMap<TcpIOer>(objMap));
  setTcpCodec(getObjFromMap<TcpCodec>(objMap));
  setUserRegisterCodec(getObjFromMap<UserRegisterCodec>(objMap));
}
